package com.powernobug.service.impl;

import com.powernobug.mapper.MarketGoodsSpecificationMapper;
import com.powernobug.service.MarketSpecificationService;
import com.powernobug.bean.model.MarketGoodsSpecification;
import com.powernobug.bean.model.MarketGoodsSpecificationExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-31
 * @Description:
 */
@Service
public class MarketSpecificationServiceImpl implements MarketSpecificationService {

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Override
    @Async("globalThreadPool")
    public Future<List<Map<String, Object>>> getSpecifMapByGoodId(Integer id) {
        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        example.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);

        List<MarketGoodsSpecification> originData = marketGoodsSpecificationMapper.selectByExample(example);
        // 新建一个结果集
        List<Map<String, Object>> finalData = new ArrayList<>();
        // 先groupingBy，获得 “规格”:List<MarketGoodsSpecification> 的Map，再重新映射到一个 “name”:"规格", “valueList”:List<MarketGoodsSpecification> 的Map
        originData.stream()
                .collect(Collectors.groupingBy(MarketGoodsSpecification::getSpecification))
                .entrySet().stream()
                // 通过ID字段对中间Map进行排序
                .sorted(Map.Entry.comparingByValue(Comparator.comparing(list -> list.get(0).getId())))
                .forEach(entry -> {finalData.add(Map.of("name", entry.getKey(), "valueList", entry.getValue()));});

        // 最终将Map<String, Object> add到结果集中 返回
        return new AsyncResult<>(finalData);
    }
}
